package org.dromara.system.utils;

import cn.hutool.core.net.URLEncodeUtil;
import cn.hutool.json.JSONObject;
import org.apache.commons.lang3.ObjectUtils;
import org.dromara.common.core.service.ConfigService;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.system.domain.bo.ArchivesBo;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 天眼查请求类
 */
@Component
public class SkyEyeExecuteUtil {
    private static final WebClient webClient;
    private static final ConfigService configService;
    private static final String AUTH_KEY = "sky.auth";
    private static String AUTH;

    static {
        configService = SpringUtils.getBean("sysConfigServiceImpl");
        webClient = WebClient.builder().baseUrl(SkyEyeProperties.URL).defaultHeader("Authorization", getAuth()).codecs(obj -> obj.defaultCodecs().maxInMemorySize(100 * 1024 * 1024)).build();
    }

    /**
     * 解密一下天眼查请求权限
     */
    private static String getAuth() {
        if(StringUtils.isEmpty(AUTH)) {
            String base64Auth = configService.getConfigValue(AUTH_KEY);
            Base64.Decoder decoder = Base64.getDecoder();
            byte[] de = decoder.decode(base64Auth.getBytes(StandardCharsets.UTF_8));
            AUTH = new String(de, StandardCharsets.UTF_8);
        }

        return AUTH;
    }

    /**
     * 执行无分页的查询
     * @param name 公司名称
     * @param path 查询路径
     */
    public static JSONObject execute(String name, String path) {
        return execute(name, path, "", "");
    }

    /**
     * 执行有分页的查询
     * @param name 公司名称
     * @param path 查询路径
     */
    public static JSONObject execute(String name, String path, String pageSize, String pageNum) {
        ArchivesBo bo = new ArchivesBo();
        bo.setKeyword(URLEncodeUtil.encode(name));
        bo.setName(URLEncodeUtil.encode(name));
        bo.setPageSize(pageSize);
        bo.setPageNum(pageNum);

        return execute(bo, path);
    }

    /**
     * 执行查询
     * @param bo 公司名称
     * @param path 查询路径
     * @return JSONObject数据
     */
    public static JSONObject execute(ArchivesBo bo, String path) {
        String PATH = SkyEyeProperties.URL + path + assembleParam(bo);
        return new JSONObject(webClient.get().uri(PATH).retrieve().bodyToMono(String.class).block());
    }

    /**
     * 组装条件
     * @param bo 查询条件
     */
    public static String assembleParam(ArchivesBo bo) {
        String param = "?";
        Class<?> clazz = ArchivesBo.class;

        // 获取并调用所有getter方法来获取属性值
        for (Method method : clazz.getMethods()) {
            if (method.getName().startsWith("get")) {
                Object value = null;
                try {
                    value = method.invoke(bo);
                } catch (IllegalAccessException | InvocationTargetException e) {
                    throw new RuntimeException(e);
                }

                if(ObjectUtils.isNotEmpty(value) && StringUtils.isNotEmpty(value.toString()) && !"getClass".equals(method.getName())) {
                    String field = lowercaseFirstLetter(method.getName().replace("get", ""));

                    if("?".equals(param)) {
                        param = "?" + field + "=" + value;
                    } else {
                        param += "&" + field + "=" + value;
                    }
                }
            }
        }

        return "?".equals(param) ? "" : param;
    }

    /**
     * 首字母转小写
     * @param str 要转换的字符串
     */
    private static String lowercaseFirstLetter(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }

        return str.substring(0, 1).toLowerCase() + str.substring(1);
    }
}
